package org.example.classtopia.Controller;

import org.example.classtopia.Model.dto.CookieDTO;
import org.example.classtopia.Service.CurriculumSyncService;
import org.example.classtopia.Service.SchoolDataService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 学校数据抓取控制器
 */
@RestController
@RequestMapping("/api")
public class SchoolDataController {

    @Autowired
    private SchoolDataService schoolDataService;

    @Autowired
    private org.example.classtopia.Service.Impl.SeleniumService seleniumService;

    @Autowired
    private CurriculumSyncService curriculumSyncService;

    /**
     * 方法一：用户手段输入Cookie，接收前端发送的Cookie，进行数据抓取
     */
    @PostMapping("/cookie")
    public ResponseEntity<Map<String, Object>> handleCookie(@RequestBody CookieDTO cookieDTO, @RequestParam Long userID) {
        Map<String, Object> response = new HashMap<>();

        try {
            // 验证Cookie是否为空
            if (cookieDTO.getCookie() == null || cookieDTO.getCookie().trim().isEmpty()) {
                response.put("success", false);
                response.put("message", "Cookie不能为空");
                return ResponseEntity.badRequest().body(response);
            }

            // 获取今天日期
            String today = java.time.LocalDate.now().toString();
            boolean success = schoolDataService.fetchCurriculumData(userID, cookieDTO.getCookie(), today);
            if (success) {
                response.put("success", true);
                response.put("message", "四周课表数据全部抓取并保存成功");
            } else {
                response.put("success", false);
                response.put("message", "课表数据获取或保存失败");
            }
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "系统异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }

        return ResponseEntity.ok(response);
    }

    /**
     * 自动化爬取并保存课表数据（Selenium方式）
     *
     * @param username 用户学号（不是真的username，而是学号）
     * @param userid   用户ID
     * @param date     日期字符串（如2024-09-01）
     * @param password 用户密码
     * @return 200，成功/失败信息
     */
    @PostMapping("/auto-curriculum")
    public ResponseEntity<Map<String, Object>> autoCurriculum(
            @RequestParam String username, // 学号，不是真的username
            @RequestParam Long userid,
            @RequestParam String date,
            @RequestParam String password) {
        Map<String, Object> response = new HashMap<>();
        try {
            // 解析起始日期，支持多种日期格式
            java.time.LocalDate startDate = parseDate(date);
            String startDateStr = startDate.toString();

            // 使用新的批量查询方法，一次性获取4周的课程数据
            Map<String, String> curriculumData = seleniumService.loginAndGetCurriculum(username, password, startDateStr);

            // 检查是否有错误
            if (curriculumData.containsKey("error")) {
                response.put("success", false);
                response.put("message", "自动化获取课表失败：" + curriculumData.get("error"));
                return ResponseEntity.ok(response);
            }

            boolean allSuccess = true;
            StringBuilder errorMsg = new StringBuilder();
            int successCount = 0;

            // 按日期顺序处理数据
            List<String> sortedDates = curriculumData.keySet().stream()
                    .sorted()
                    .collect(java.util.stream.Collectors.toList());

            for (int i = 0; i < sortedDates.size(); i++) {
                String dateKey = sortedDates.get(i);
                String json = curriculumData.get(dateKey);

                // 检查单个日期的数据是否有效
                if (json == null || json.trim().isEmpty() || json.contains("获取日期") && json.contains("出错")) {
                    allSuccess = false;
                    errorMsg.append("[").append(dateKey).append("]自动化获取课表失败；");
                    continue;
                }

                try {
                    // 第一次调用时清空数据，后续调用只追加
                    boolean success = schoolDataService.saveCurriculumFromJson(json, userid, i == 0);
                    if (success) {
                        successCount++;
                    } else {
                        allSuccess = false;
                        errorMsg.append("[").append(dateKey).append("]课表数据保存失败；");
                    }
                } catch (Exception e) {
                    allSuccess = false;
                    errorMsg.append("[").append(dateKey).append("]数据处理异常：").append(e.getMessage()).append("；");
                }
            }

            // 构造响应结果
            if (allSuccess && successCount > 0) {
                response.put("success", true);
                response.put("message", String.format("成功抓取并保存了%d周的课表数据", successCount));
                response.put("details", String.format("处理日期范围：%s 到 %s",
                        sortedDates.isEmpty() ? "无" : sortedDates.get(0),
                        sortedDates.isEmpty() ? "无" : sortedDates.get(sortedDates.size() - 1)));
            } else if (successCount > 0) {
                response.put("success", true);
                response.put("message", String.format("部分成功：成功处理%d周，失败详情：%s",
                        successCount, errorMsg.toString()));
            } else {
                response.put("success", false);
                response.put("message", errorMsg.length() > 0 ?
                        "全部失败：" + errorMsg.toString() : "未能获取任何有效的课表数据");
            }

            try {
                curriculumSyncService.syncCurriculumToCourse(userid);
                //return "同步成功";
            } catch (Exception e) {
                //return "同步失败：" + e.getMessage();
            }

            return ResponseEntity.ok(response);

        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "系统异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 解析日期字符串，支持多种格式
     *
     * @param dateStr 日期字符串，支持格式：yyyy-MM-dd, yyyy-M-d, yyyy/MM/dd, yyyy/M/d
     * @return LocalDate对象
     */
    private java.time.LocalDate parseDate(String dateStr) {
        if (dateStr == null || dateStr.trim().isEmpty()) {
            throw new IllegalArgumentException("日期不能为空");
        }

        // 尝试多种日期格式
        java.time.format.DateTimeFormatter[] formatters = {
                java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd"),
                java.time.format.DateTimeFormatter.ofPattern("yyyy-M-d"),
                java.time.format.DateTimeFormatter.ofPattern("yyyy/MM/dd"),
                java.time.format.DateTimeFormatter.ofPattern("yyyy/M/d")
        };

        for (java.time.format.DateTimeFormatter formatter : formatters) {
            try {
                return java.time.LocalDate.parse(dateStr.trim(), formatter);
            } catch (java.time.format.DateTimeParseException e) {
                // 继续尝试下一种格式
            }
        }

        throw new IllegalArgumentException("日期格式不正确，支持格式：yyyy-MM-dd, yyyy-M-d, yyyy/MM/dd, yyyy/M/d，输入的日期：" + dateStr);
    }
}
